<?php
/**
 * Created by PhpStorm.
 * User: coffee
 * Date: 2018/1/9
 * Time: 上午10:23
 */

namespace App\Http\Controllers;

use App\Exceptions\EventAppliedException;
use App\Exceptions\InvaildAppliedException;
use App\Exceptions\UserEventNotFoundException;
use App\Facades\Consumer;
use App\Http\Response\OKResponse;
use App\Models\EventStudentCalendarPresent;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AdminEventsController extends Controller
{
    // allow event id 1000
    public function allowStudentCalendarPresent(Request $request)
    {
        $this->validate($request, [
            'studentId' => 'required|integer',
        ]);

        $body = [
            'student_id' => intval($request->input('studentId')),
            'event_id'   => EventStudentCalendarPresent::EVENT_ID,
        ];
        //firstOrNew效率更好  并发问题 还是用firstOrCreated安全
        $studentEvent = EventStudentCalendarPresent::firstOrCreate($body);
        if ($studentEvent->getStatus() == EventStudentCalendarPresent::STATUS_Prohibit)
            $studentEvent->setStatus(EventStudentCalendarPresent::STATUS_Allow);
        $studentEvent->setAdminId(Consumer::getUserId());
        $studentEvent->save();

        return new OKResponse();
    }

    public function retrieveStudentCalendarPresent(Request $request)
    {
        $this->validate($request, [
            "studentId" => "integer",
            "status"    => "integer|in:0,1,2,3,4,5",
            "page"      => "integer|min:1",
            "pageSize"  => "integer|max:100|min:5",
            "telephone" => "string",
        ]);

        $query = EventStudentCalendarPresent::query();
        if ($request->has("studentId")) {
            $query->where("student_id", intval($request->input("studentId")));
        }

        if ($request->has("status")) {
            $query->where("status", intval($request->input("status")));
        }

        if ($request->has("telephone")) {
            $query->where("telephone", $request->input("telephone"));
        }

        $total = $query->count();
        $page = intval($request->input("page", 1));
        $pageSize = intval($request->input("pageSize", 10));
        $events = $query->skip($pageSize * ($page - 1))->take($pageSize)->get();
        $result = [];
        foreach ($events as $item) {
            $result[] = [
                'id'        => $item->getId(),
                'studentId' => $item->getStudentId(),
                'eventId'   => $item->getEventId(),
                'status'    => $item->getStatus(),
                'name'      => $item->getName(),
                'telephone' => $item->getTelephone(),
                'address'   => $item->getAddress(),
                'province'  => $item->getProvince(),
                'city'      => $item->getCity(),
                'adminId'   => $item->getAdminId(),
            ];
        }

        return new JsonResponse([
            "total"    => $total,
            "page"     => $page,
            "pageSize" => $pageSize,
            "result"   => $result,
        ]);
    }

    public function deleteStudentCalendarPresent(Request $request)
    {
        $this->validate($request, [
            'studentId' => 'required|integer',
        ]);

        $event = EventStudentCalendarPresent::whereStudentIdAndEventId(
            intval($request->input('studentId')),
            EventStudentCalendarPresent::EVENT_ID
        )->first();

        if (empty($event)) {
            throw new UserEventNotFoundException();
        }

        $event->setAdminId(Consumer::getUserId());
        $event->setStatus(EventStudentCalendarPresent::STATUS_Prohibit);
        $event->save();
    }

    public function updateStudentCalendarPresent(Request $request)
    {
        $this->validate($request, [
            'studentId' => 'required|integer',
            'name'      => 'string',
            'telephone' => 'integer|regex:/^(\+86)?1[34578][0-9]{9}$/',
            'province'  => 'string',
            'city'      => 'string',
            'address'   => 'string',
        ]);

        $record = EventStudentCalendarPresent::where('student_id', intval($request->input('studentId')))->first();

        if (empty($record))
            throw new UserEventNotFoundException();

        $status = $record->getStatus();
        if (
            $status !== EventStudentCalendarPresent::STATUS_Allow &&
            $status !== EventStudentCalendarPresent::STATUS_Created
        ) {
            throw new EventAppliedException();
        }

        if ($request->has('name'))
            $record->setName($request->input('name'));
        if ($request->has('telephone'))
            $record->setTelephone($request->input('telephone'));
        if ($request->has('address'))
            $record->setAddress($request->input('address'));
        if ($request->has('province'))
            $record->setProvince($request->input('province'));
        if ($request->has('city'))
            $record->setCity($request->input('city'));

        $record->setAdminId(Consumer::getUserId());
        $record->save();

        return new OKResponse();
    }

    //2018送年历
    public function createStudentCalendarPresentEvent(Request $request)
    {
        $this->validate($request, [
            'studentId' => 'required|integer',
            'city'      => 'required|string',
            'province'  => 'required|string',
            'name'      => 'required|string',
            'telephone' => 'required|string|regex:/^(\+86)?1[34578][0-9]{9}$/',
            'address'   => 'required|string',
        ]);

        $studentId = intval($request->input('studentId'));
        $studentEvent = EventStudentCalendarPresent::firstOrCreate([
            'student_id' => $studentId,
            'event_id'   => EventStudentCalendarPresent::EVENT_ID,
        ]);

        if (!empty($studentEvent)) {
            $status = $studentEvent->getStatus();
            if (
                $status == EventStudentCalendarPresent::STATUS_Prohibit ||
                $status == EventStudentCalendarPresent::STATUS_Exception
            ) {
                throw new InvaildAppliedException();
            }

            if (
                $status == EventStudentCalendarPresent::STATUS_Post ||
                $status == EventStudentCalendarPresent::STATUS_Success
            ) {
                return new OKResponse();
            }
        }

        if (empty($studentEvent)) {
            $studentEvent->setStudentId($studentId);
            $studentEvent->setEventId(EventStudentCalendarPresent::EVENT_ID);
        }

        $studentEvent->setName($request->input('name'));
        $studentEvent->setTelephone($request->input('telephone'));
        $studentEvent->setAddress($request->input('address'));
        $studentEvent->setProvince($request->input('province'));
        $studentEvent->setCity($request->input('city'));
        $studentEvent->setStatus(EventStudentCalendarPresent::STATUS_Created);
        $studentEvent->save();

        return new OKResponse();
    }
}
